package com.booleansoft.redirect;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import org.slf4j.LoggerFactory;

import com.booleansoft.redirect.cmmd.BaseCommand;
import com.booleansoft.util.XTCoding;

public class CommandServer extends Thread{
	public static volatile int started=0;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			startUp();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	int interapte=0;
	private void startRedirect(){
		int[] ports=DirectContext.getInstance().getFromport();
		for(int port:ports){
			Runner r=new Runner(port);
			Runner.Runners.add(r);
			r.start();
		}
	}
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CommandServer.class);
	public synchronized void startUp() throws Exception{
			if(started==1){
				return;
			}
			startRedirect();
			int p=DirectContext.getInstance().getCmdport();
			ServerSocket socketServer=new ServerSocket(p);
			started=1;
			logger.info("命令行端口@port"+p);
			System.out.println("命令行端口@port"+p);
			while(true){
				if(interapte==1){
					break;
				}
				Socket socket=null;
				try {
					socket=socketServer.accept();
					new Thread(new ThreadServerRunable(socket)).start();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		
		
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new CommandServer().start();
		int port=DirectContext.getInstance().getCmdport();
		Socket	client=null;
		try {
			BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
			DataInputStream in=null;
			String str="";
			DataOutputStream out=null;
			boolean flag=false;
			while((str=reader.readLine())!=null){
				if(str.trim().equals("")){
					continue;
				}
				if(!flag){
					if(!str.startsWith("login ")){
						continue;
					}
					client=new Socket("localhost",port);
					out=new DataOutputStream(client.getOutputStream());
					out.writeUTF(str);
					in=new DataInputStream(client.getInputStream());
					if(!"ok".equals(in.readUTF())){
						continue;
					}
					flag=true;
					System.out.println("登陆成功!");
					continue;
				}
				out.writeUTF(str);
				System.out.println(in.readUTF());
				if(str.equals("exit")){
					flag=false;
					try {
						in.close();
					} catch (Exception e) {}
					try {
						out.close();
					} catch (Exception e) {}
					try {
						client.close();
					} catch (Exception e) {}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				client.close();
			} catch (Exception e) {}
		}
	}
}
